/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jwu2.indexserver;

import java.io.IOException;
import java.net.*;
import jwu2.log.Logger;

/**
 *
 * @author Rolf
 */
public class IndexServerCore implements Runnable {
    
    private static final String SERVER_VERSION = "1";
    private static final int SERVER_PORT = 4260;
    
    private static IndexServerCore singleton;

    public static String getSERVER_VERSION() {
        return SERVER_VERSION;
    }
    
    /**
     * Get the singleton server (Starting it if it isnt running) 
     * @return the singleton server
     */
    public static IndexServerCore singleton() {
        
        startServer();
        
        return singleton;
    }
    
    private boolean serverRunning;
    
    private IndexServerCore() {
        serverRunning = false;
    }
    
    public static void startServer() {
        if(singleton == null) {
            singleton = new IndexServerCore();
            
            singleton.setServerRunning(true);
            
            //Start listener thread
            new Thread(singleton).start();
            
            //Start fetcher threads
            IndexServerFetcherThread.startIndexFetcherThreads();
        }
    }
    
    public void run() {
        
        Logger.logln("JWU2 Index Server starting on port ["+SERVER_PORT+"]...");
        
        try {
            ServerSocket server = new ServerSocket(SERVER_PORT);
            while(isServerRunning()) {
                
                //Accept an incomming connection
                Socket s = server.accept();
                
                //Spawn a thread to handle the communication with client
                new Thread(new IndexServerConnectionThread(s)).start();
            }
        }
        catch (IOException ex) {
            Logger.logln("Error creating server on port ["+SERVER_PORT+"]: "+ex);
        }
        
        Logger.logln("JWU2 Index Server shutting down...");
    }

    public boolean isServerRunning() {
        return serverRunning;
    }

    public void setServerRunning(boolean serverRunning) {
        this.serverRunning = serverRunning;
    }
}
